package com.zjlp.im.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.zjlp.im.netty.wrapper.MsgWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

public class DefaultClientHandler extends ChannelInboundHandlerAdapter {
    //用户
    private String user;
    //聊天对象
    private String client;

    public DefaultClientHandler(String user, String client) {
        this.user = user;
        this.client = client;
    }

    private JSONObject msgContent = null;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 写数据
        System.out.println(user + "给服务端发送登录消息!");
        MsgWrapper wrapper = this.wrapperLoginMsgInfo();
        String content = JSONObject.toJSONString(wrapper);
        ByteBuf jsonContent = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, content);
        ChannelFuture cf = ctx.channel().writeAndFlush(jsonContent);
        cf.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("客户端用户【" + user + "】成功发送登录消息！");
                ctx.fireUserEventTriggered("chatEvent");

            }
        });
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
        ByteBuf buf = (ByteBuf) msg;
        String content=new String(ByteBufUtil.getBytes(buf),"UTF-8");
        System.out.println("獲取用戶的值是"+content);
        msgContent = JSONObject.parseObject(content);
        System.out.println("Netty-Server:Receive Message," + msgContent.toJSONString());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("读取完消息了，回复消息！！");
        ctx.fireUserEventTriggered("chatEvent");
        ctx.fireChannelReadComplete();
    }


    /**
     *
     * @return
     */
    private MsgWrapper wrapperLoginMsgInfo() {
        MsgWrapper msgWrapper = new MsgWrapper();
        msgWrapper.setType(1);
        msgWrapper.setUser(user);
        return msgWrapper;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
